package com.bookstore.servlet.validate;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONObject;

import com.bookstore.model.User;
import com.bookstore.service.ServiceFactory;

@WebServlet("/validateEmail.do")
public class ValidateEmailServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private boolean flag;

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String email = request.getParameter("email");

		User user;
		try {
			user = ServiceFactory.getUserService().findByEmail(email);
			if (user != null) {
				flag = false;
			} else {
				flag = true;
			}
			
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("flag", flag);
			PrintWriter out = response.getWriter();
			out.print(jsonObject.toString());
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
